package co.sanduche.teach;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import co.sanduche.models.Enums;
import co.sanduche.models.Enums.ChannelType;
import co.sanduche.teach.gallery.AndroidStudent;
import co.sanduche.teach.gallery.ImageItem;
import co.sanduche.teach.gallery.PhotoFragment;
import co.sanduche.util.EPBaseActivity;
import co.sanduche.util.EPBaseAdapter;
import co.sanduche.vos.Tuple;

public class PostActivity extends EPBaseActivity implements
		OnQueryTextListener, OnClickListener {
	static final String STUDENTS_KEY = "students";
	private static final String QUERY_KEY = "query";
	private static final String ALL_CB = "ALL_CB";
	private boolean all;

	private EPBaseAdapter studentsAdapter;
	private List<Tuple<AndroidStudent, Boolean>> filteredStudents = new ArrayList<Tuple<AndroidStudent, Boolean>>();
	private ArrayList<Tuple<AndroidStudent, Boolean>> students;
	private String query;
	private ImageItem imageItem;
	private PostPresenter presenter;
	private ImageButton btnPost;

	public PostActivity() {
		super("Publicar");
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		imageItem = (ImageItem) getIntent().getSerializableExtra(
				PhotoFragment.IMAGE_ITEM_KEY);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_post);
		ListView lv = (ListView) findViewById(R.id.postListStudents);
		btnPost = (ImageButton) findViewById(R.id.postBtnPost);

		btnPost.setOnClickListener(this);

		studentsAdapter = new EPBaseAdapter(this, R.layout.item_student1) {
			private CheckBox allCB;

			@Override
			public int getCount() {
				if (filteredStudents != null)
					return filteredStudents.size() + 1;
				return 1;
			}

			@Override
			public void initView(final int position, View view) {
				final int p = position - 1;
				final CheckBox cb = (CheckBox) view
						.findViewById(R.id.postCheck);
				Log.d("ASD", "" + cb);
				TextView name = (TextView) view.findViewById(R.id.postLblName);
				ImageView img = (ImageView) view.findViewById(R.id.postImg);
				if (position == 0) {
					name.setText("Todos");
					cb.setChecked(all);
					img.setVisibility(View.VISIBLE);
					img.setImageResource(R.drawable.ic_launcher);
					allCB = cb;
					allCB.setTag(ALL_CB);
				} else {

					img.setVisibility(View.GONE);

					name.setText(filteredStudents.get(p).getX().getName());
					cb.setChecked(filteredStudents.get(p).getY());
					cb.setTag(null);
				}

				View.OnClickListener listener = new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						if (position == 0) {
							all = !all;
							for (int i = 0; i < filteredStudents.size(); i++)
								filteredStudents.get(i).setY(all);
							notifyDataSetChanged();
						} else {
							Tuple<AndroidStudent, Boolean> tupleStudentCheck = filteredStudents
									.get(p);
							tupleStudentCheck.setY(!tupleStudentCheck.getY());

							cb.setChecked(tupleStudentCheck.getY());
							all = false;
							if (allCB != null && ALL_CB.equals(allCB.getTag()))
								allCB.setChecked(all);
						}
					}
				};
				cb.setOnClickListener(listener);
				view.setOnClickListener(listener);
			}
		};
		lv.setAdapter(studentsAdapter);

		presenter = new PostPresenter(this);
		try {
			if (savedInstanceState != null) {
				this.students = (ArrayList<Tuple<AndroidStudent, Boolean>>) savedInstanceState
						.getSerializable(PostActivity.STUDENTS_KEY);
				for (Tuple<AndroidStudent, Boolean> t : students)
					filteredStudents.add(t);
				onQueryTextChange(savedInstanceState.getString(QUERY_KEY));
			} else {
				presenter.init();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_post, menu);
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));

		searchView.setOnQueryTextListener(this);

		// Applies white color on searchview text
		int id = searchView.getContext().getResources()
				.getIdentifier("android:id/search_src_text", null, null);
		TextView textView = (TextView) searchView.findViewById(id);
		textView.setTextColor(getResources().getColor(
				R.color.kiido_actionbar_text_color));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void setStudentsList(final List<AndroidStudent> students) {

		this.students = new ArrayList<Tuple<AndroidStudent, Boolean>>();
		for (AndroidStudent as : students) {
			Tuple<AndroidStudent, Boolean> tuple = new Tuple<AndroidStudent, Boolean>(
					as, false);
			this.filteredStudents.add(tuple);
			this.students.add(tuple);
		}

		studentsAdapter.notifyDataSetChanged();

	}

	@Override
	public boolean onQueryTextChange(String query) {
		this.query = query;
		if (query == null)
			return false;
		String[] words = query.toLowerCase().trim().split(" +");
		filteredStudents.clear();
		for (Tuple<AndroidStudent, Boolean> tuple : students) {
			boolean passes = true;
			String name = tuple.getX().getName().toLowerCase();
			for (String word : words) {
				if (!name.contains(word)) {
					passes = false;
					break;
				}
			}
			if (passes) {
				filteredStudents.add(tuple);
			}
		}
		studentsAdapter.notifyDataSetChanged();
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable(STUDENTS_KEY, students);
		outState.putString(QUERY_KEY, query);
	}

	@Override
	public void onClick(View arg0) {
		btnPost.setOnClickListener(null);
		List<Tuple<ChannelType, Long>> channels = new ArrayList<Tuple<ChannelType, Long>>();
		for (Tuple<AndroidStudent, Boolean> as : students) {
			if (as.getY())
				channels.add(new Tuple<Enums.ChannelType, Long>(
						ChannelType.STUDENT, as.getX().getId()));
		}
		Log.d("postingTesting", "pasa");
		List<Long> photos = Arrays.asList(imageItem.getId());
		presenter.postPost(channels, photos);
		this.finish();

	}
}
